package com.ruoyi.common.utils.sql;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.utils.DateUtils;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author Administrator
 */
public class DbOperate {
    /**
     * @param host ip
     * @param port 端口
     * @param userName 用户名
     * @param password 密码
     * @param dbName 数据库名
     * @param dir  存放目录
     * @param fileName 备份数据库文件名  ddd-日期.sql
     * @throws IOException 输入输出异常
     */
    public static void backUp(String host,String port,String userName,String password,String dbName,String dir,String fileName) throws IOException {
        File file = new File(dir);
        if(!file.exists()){
            file.mkdirs();
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysqldump");
        stringBuilder.append(" -h ").append(host);
        stringBuilder.append(" -P ").append(port);
        stringBuilder.append(" -u ").append(userName);
        stringBuilder.append(" -p").append(password);
        stringBuilder.append(" ").append(dbName);
        stringBuilder.append(" > ").append(dir+"/"+fileName);
        String[] commands = new String[4];
        //获取系统名称
        String property = System.getProperty("os.name");
        if(property.startsWith("Linux")){
            String command= stringBuilder.toString();
            commands= new String[]{"/bin/sh", "-c",command };
        }if(property.startsWith("Windows")){
            String command= stringBuilder.toString();
            commands= new String[]{"cmd", "/c", command};
        }
        Runtime.getRuntime().exec(commands);
    }


   public static void main(String[] args) throws IOException {
       backUp("127.0.0.1","3306","root","123456","a0723","D:\\ruoyi\\sql\\","a0723-"+ DateUtils.dateTimeNow() +".sql");
    }
}
